import Util from './utils';
import Session from './session';

class File {
    constructor() {}
    getAuthSetting() {
        return new Promise((resolve, reject) => {
            uni.getSetting({
                success(settingRes) {
                    // 判断是否已授权
                    let permissions = null;
                    let permissionsKey = '';

                    // #ifdef MP-TOUTIAO
                    permissionsKey = 'scope.album';
                    permissions = settingRes.authSetting['scope.album'];
                    // #endif

                    // #ifndef MP-TOUTIAO
                    permissionsKey = 'scope.writePhotosAlbum';
                    permissions =
                        settingRes.authSetting['scope.writePhotosAlbum'];
                    // #endif

                    if (!permissions) {
                        uni.authorize({
                            scope: permissionsKey,
                            success: () => {
                                resolve();
                            },
                            fail: (err) => {
                                uni.showModal({
                                    title: '温馨提示',
                                    content: '您没有授权，无法使用保存',
                                    showCancel: false,
                                    confirmText: '去授权',
                                    success: (res) => {
                                        if (res.confirm) {
                                            uni.openSetting({
                                                success: (res) => {
                                                    resolve(true);
                                                }
                                            });
                                        } else {
                                            resolve();
                                        }
                                    }
                                });
                            }
                        });
                    } else {
                        resolve();
                    }
                }
            });
        });
    }
    async saveToAlbum(type, filePath) {
        if (type === 'video') {
            await uni.saveVideoToPhotosAlbum({ filePath: filePath });
        } else {
            await uni.saveImageToPhotosAlbum({ filePath: filePath });
        }
    }

    async saveFileByUrl(url) {
        const res = await uni.downloadFile({ url });

        if (res.statusCode === 200) {
            await this.getAuthSetting();

            const fileType = Util.getFileType(url);
            await this.saveToAlbum(
                fileType === 'video' ? 'video' : 'image',
                res.tempFilePath
            );
        } else {
            throw new Error(`文件下载失败，状态码：${res.statusCode}`);
        }
    }

    async saveFile(url) {
        uni.showLoading({ title: '保存中' });

        try {
            await this.saveFileByUrl(url);

            uni.hideLoading();

            uni.showToast({
                title: '保存成功',
                icon: 'success'
            });
        } catch (err) {
            uni.hideLoading();

            if (!(err && err.errMsg && err.errMsg.includes('cancel'))) {
                uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                });
                console.error('文件保存失败 --->', err);
            }
        }
    }
    async saveMultipleFiles(urls) {
        let current = 0;
        const total = urls.length;

        for (const url of urls) {
            try {
                uni.showLoading({
                    title: `保存中 (${++current}/${total})`
                });

                await this.saveFileByUrl(url);
            } catch (err) {
                uni.hideLoading();

                if (!(err && err.errMsg && err.errMsg.includes('cancel'))) {
                    console.error('文件保存失败 --->', err);
                    uni.showToast({
                        title: `保存失败 (${current}/${total})`,
                        icon: 'none'
                    });
                }
                return;
            }
        }

        uni.hideLoading();
        uni.showToast({
            title: '保存成功',
            icon: 'success'
        });
    }

    uploadFile(url) {
        return this.upload({tempFilePath: url});
    }

    // 文件上传新接口
    upload({tempFilePath, path, ttl}) {
        return new Promise((resole, reject) => {
            uni.uploadFile({
                url: 'https://api.ali-fc.moapp.net.cn/service/uniapp_base/file',
                filePath: tempFilePath,
                name: 'file',
                timeout: 20000,
                formData: {
                    path: `${Session.getAppid()}${path ? '/' + path : ''}`,
                    ttl: ttl || '30d'
                },
                success: (res) => {
                    if (res.data) {
                        const pkg = JSON.parse(res.data);
                        if (pkg.code == 'SUCCESS') {
                            resole({
                                msg: pkg.code,
                                url: pkg.data.url
                            });
                        } else {
                            reject({
                                msg: pkg.code,
                                url: ''
                            });
                        }
                    } else {
                        reject();
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }
}

const file = new File();

export default file;
